#include <stdint.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/select.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include "utility.h"
int select_call(int32_t sk, int32_t seconds, int32_t usec) {
   fd_set fdvar;
   struct timeval timeout;
   timeout.tv_sec = seconds;
   timeout.tv_usec = usec;

   FD_ZERO( &fdvar);
   FD_SET(sk,&fdvar);
   if( select( sk + 1, &fdvar,NULL,NULL,&timeout) == -1) {
      return -1;
   }
   if( FD_ISSET( sk, &fdvar )){
      return 1;
   }
   else {
      return 0;
   }
}
int send_mesg( int32_t sk, uint16_t type, uint16_t flags, 
      uint16_t size, uint16_t uid, const char* buf) 
{
   Message m;
   if( size > MAX_MESSAGE ) {
      errno = EINVAL;
      return -1;
   }
   m.version = VERSION;
   m.sender = uid; 
   m.type = htons(type);
   m.flags = htons(flags);
   m.size = htons(size);
   memcpy(m.message, buf, size );

   if( send( sk, &m, sizeof( Message ) - MAX_MESSAGE + size,0) == -1 ) {
      return -1;
   }

   return 0;
}
int recv_mesg( int32_t sk, Message &m ) {

   int bytesread;
   if( (bytesread = recv( sk, &m, sizeof(m), 0)) == -1 ) {
      return -1;
   }
   
   m.version = m.version;
   m.sender = m.sender; 
   m.type = ntohs(m.type);
   m.flags = ntohs(m.flags);
   m.size = ntohs(m.size);
   m.message[m.size] = '\0';
   return bytesread;
}
